﻿@{
    Layout = "~/Views/Shared/_FormWhite.cshtml";
}
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment HostingEnvironment
@section header{
    <link href="@Url.Content("~/lib/summernote/0.8.15/summernote.min.css")" rel="stylesheet" type="text/css">
    <script src='@Url.Content("~/lib/summernote/0.8.15/summernote.js")' type="text/javascript"></script>
    <script src='@Url.Content("~/lib/summernote/0.8.15/lang/summernote-zh-CN.min.js")' type="text/javascript"></script>

    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/imageupload/1.0/css/imgup.min.css"))
    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/imageupload/1.0/js/imgup.min.js"))

    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/bootstrap.tagsinput/0.8.0/bootstrap-tagsinput.min.css"))
    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/bootstrap.tagsinput/0.8.0/bootstrap-tagsinput.min.js"))


     <!--引入 element-ui 的样式，-->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 必须先引入vue，  后使用element-ui -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
    <!-- 引入element 的组件库-->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>

    <style type="text/css">
        .el-upload__input {
    display: none !important;
}
        .custom-upload {
  display: inline-block;
}

.custom-upload .el-upload__tip {
  display: none; /* 隐藏提示文本 */
}

.custom-upload .el-upload-list__item-name {
  display: none; /* 隐藏文件名 */
}

.custom-upload .el-upload-list__item-thumbnail {
  display: none; /* 隐藏文件缩略图 */
}

.custom-uploads .el-upload--picture-card {
  width: 148px;
  height: 148px;
}
    </style>
}
<div id="app" class="wrapper animated fadeInRight">
    <el-form ref="form" style="margin-top:20px" :model="form" label-width="120px">
          <el-form-item label="产品种类">
            <el-input v-model="form.type_name"></el-input>
          </el-form-item>
          <el-form-item label="开启品牌型号">
            <el-switch v-model="form.IsBrandModel" active-text="是" inactive-text="否" active-value="1" inactive-value="0"></el-switch>
          </el-form-item>
          <el-form-item v-if="form.IsBrandModel==1" label="品牌型号">
             <el-table
                        :data="form.TypeBrandList"
                        border
                        size="mini"
                        style="width: 100%">
                        <el-table-column prop="brandname" align="center" label="品牌"></el-table-column>
                        <el-table-column prop="modellist" align="center" label="型号集"></el-table-column>
                        <el-table-column
                          prop="CZ">
                          <template slot="header" slot-scope="scope">
                                <el-button type="primary" size="mini" v-on:click="handleAddTypeBrand" icon="el-icon-circle-plus-outline">添加</el-button>
                              </template>
                              <template slot-scope="scope">
                                <el-button
                                  size="mini"
                                  type="danger"
                                  v-on:click="handleDelete(scope.$index, scope.row)">删除</el-button>
                              </template>
                        </el-table-column>
                  </el-table>
          </el-form-item>
     </el-form>

    <el-dialog title="品牌型号"  :modal="false" :visible.sync="TypeBrandVisible" :append-to-body="true">
          <el-cascader
            ref="cascader"
            v-model="selectedValues"
            :options="typebrand"
            v-on:change="handleCascaderChange"
            :props="{ multiple: true,checkStrictly:false}"
            clearable>
        </el-cascader>

          <div slot="footer" class="dialog-footer">
            <el-button v-on:click="typeBrandCancel">取 消</el-button>
            <el-button type="primary"  v-on:click="typeBrandSubmit">确 定</el-button>
          </div>
        </el-dialog>
</div>

<script type="text/javascript">
    var id = ys.request("id");

    var vm = new Vue({
        el: '#app',  // 挂载到 id 为 app 的元素
        data: {
            form: {
                type_name: '',
                IsBrandModel: '0',
                TypeBrandList: [
                ]
            },
            typebrand: [],
            selectedValues: [], // 用于 v-model 绑定的值路径
            selectedNodes: [],
            TypeBrandVisible: false
        },
        methods: {
             handleCascaderChange(valuePaths) {
  // 构建初始结果数组
  const initialResult = valuePaths.map(path => {
    return this.buildNodeStructure(path, this.typebrand, path.length - 1);
  });

  // 合并相同的父节点并删除空 children
  this.selectedNodes = this.mergeNodes(initialResult);
  console.log(JSON.stringify(this.selectedNodes));
},

buildNodeStructure(path, tree, index) {
  if (index < 0) {
    return null;
  }

  const value = path[index];
  const node = this.findNode(tree, value);

  if (node) {
    const currentNode = { value: node.value, label: node.label, children: [] };

    // 递归构建父节点的结构
    const parent = this.buildNodeStructure(path, tree, index - 1);
    if (parent) {
      parent.children.push(currentNode);
      return parent;
    }

    return currentNode;
  }

  return null;
},

findNode(tree, value) {
  if (!tree) return null;
  for (let node of tree) {
    if (node.value === value) {
      return node;
    }
    const child = this.findNode(node.children, value);
    if (child) {
      return child;
    }
  }
  return null;
},

mergeNodes(nodes) {
  const mergedNodes = [];
  const parentMap = new Map();

  nodes.forEach(node => {
    const parentValue = node.value;
    if (parentMap.has(parentValue)) {
      // 找到已存在的父节点
      const existingNode = parentMap.get(parentValue);
      existingNode.children.push(...node.children);
    } else {
      // 新的父节点
      parentMap.set(parentValue, node);
      mergedNodes.push(node);
    }
  });

  // 递归删除空 children
  //this.removeEmptyChildren(mergedNodes);

  return mergedNodes;
},
            //handleCascaderChange(value) {
            //    // 构建初始结果数组
            //    var  that = this;
            //    const initialResult = valuePaths.map(path => {
            //        return this.buildNodeStructure(path, this.typebrand, path.length - 1);
            //    });
                
            //    //this.updateParentAndChildrenSelection(initialResult);
            //    // 合并相同的父节点并删除空 children
            //    this.selectedNodes = this.mergeNodes(initialResult);
            //    //this.getSelectedNodes();
            //    console.log(JSON.stringify(this.selectedNodes));
                
            //},
            //getSelectedNodes() {
            //    if (this.$refs.cascader) {
            //        this.selectedNodes = this.$refs.cascader.getCheckedNodes(false,false);
            //    }
            //},
            // buildNodeStructure(path, tree, index) {
            //     if (index < 0) {
            //         return null;
            //     }
            //     const value = path[index];
            //     const node = this.findNode(tree, value);

            //     if (node) {
            //         const currentNode = { value: node.value, label: node.label, children: [] };
            //         // 递归构建父节点的结构
            //         if (index >0) {
            //             const parent = this.buildNodeStructure(path, tree, index - 1);
            //             if (parent) {
            //                 parent.children.push(currentNode);
            //                 return parent;
            //             }
            //         }
            //         else
            //         {
            //             return node;
            //         }
            //     }
            //     return null;
            // },
            // findNode(tree, value) {
            //     if (!tree) return null;
            //     for (let node of tree) {
            //         if (node.value === value) {
            //             //将父节点children 设置成空
            //             //const nodenew = { value: node.value, label: node.label, children: [] };
            //             return node;
            //         }
            //         const child = this.findNode(node.children, value);
            //         if (child) {
            //             return child;
            //         }
            //     }
            //     return null;
            // },
            // mergeNodes(nodes) {
            //     const mergedNodes = [];
            //     const parentMap = new Map();

            //     nodes.forEach(node => {
            //         const parentValue = node.value;
            //         if (parentMap.has(parentValue)) {
            //             // 找到已存在的父节点
            //             const existingNode = parentMap.get(parentValue);
            //             existingNode.children.push(...node.children);
            //         } else {
            //             // 新的父节点
            //             parentMap.set(parentValue, node);
            //             mergedNodes.push(node);
            //         }
            //     });

            //     // 递归删除空 children
            //     //为空节点不用删除（取消为空节点）
            //     //this.removeEmptyChildren(mergedNodes);

            //     return mergedNodes;
            // },
             removeEmptyChildren(nodes) {
                 nodes.forEach(node => {
                     if (node.children && node.children.length === 0) {
                         delete node.children;
                     } else {
                         this.removeEmptyChildren(node.children);
                     }
                 });
            },
            //updateParentAndChildrenSelection(nodes) {
            //    nodes.forEach(node => {
            //        if (node.children && node.children.length > 0) {
            //            console.log('node.value:', node.value, typeof node.value);
            //            console.log('this.selectedValues:', this.selectedValues);
            //            console.log('this.selectedValuesJson:', JSON.stringify(this.selectedValues));
            //            console.log('this.selectedValues[0].value:', this.selectedValues[0], typeof this.selectedValues[0]);
            //            const nodeValue = String(node.value);
            //            const isIncluded = this.selectedValues.some(item => item.includes(nodeValue));
            //            // 如果父节点被选中，递归选中所有子节点
            //            if (isIncluded) {
            //                this.selectAllChildren(node);
            //            } else {
            //                // 如果父节点被取消，递归取消所有子节点
            //                this.deselectAllChildren(node);
            //            }
            //        }
            //    });
            //},
            //selectAllChildren(node) {
            //    if (node.children && node.children.length > 0) {
            //        node.children.forEach(child => {
            //            const nodeValue = String(child.value);
            //            const isIncluded = this.selectedValues.some(item => item.includes(nodeValue));
            //            if (!isIncluded) {
            //                this.selectedValues.push([node.value,child.value]);
            //            }
            //            this.selectAllChildren(child);
            //        });
            //    }
            //},
            //deselectAllChildren(node) {
            //    if (node.children && node.children.length > 0) {
            //        node.children.forEach(child => {
            //            const nodeValue = String(child.value);
            //            const isIncluded = this.selectedValues.some(item => item.includes(nodeValue));
            //            if (isIncluded) {
            //                this.selectedValues.forEach((item, index) => {
            //                    if (item.includes(nodeValue)) {
            //                        selectedValues.splice(index, 1);
            //                    }
            //                });
            //            }
            //            this.deselectAllChildren(child);
            //        });
            //    }
            //},
             handleDelete(index, row) {
                this.form.TypeBrandList.splice(index, 1);
             },
             handleAddTypeBrand() {
                 //this.selectedValues = [];
                 //this.selectedNodes = [];
                 this.TypeBrandVisible = true;
             },
             getForm() {
                   var that = this;
                   ys.ajax({
                    url: '@Url.Content("~/QixingManage/GoodsTypes/GetFormJson")' + '?id=' + id,
                    type: 'get',
                    success: function (obj) {
                        if (obj.Tag == 1) {
                            that.form.type_name = obj.Data.type_name;
                            that.form.IsBrandModel =""+obj.Data.IsBrandModel;
                            if (obj.Data.IsBrandModel=="1")
                            {
                                that.selectedValues = JSON.parse(obj.Data.input_selectedValues);
                                that.selectedNodes = JSON.parse(obj.Data.input_BrandList);
                                that.selectedNodes.forEach(function(item) {
                                    var brandname = item.label;
                                    var brandid = item.value;
                                    if (item.children != null && item.children.length > 0) {
                                        var modellist = item.children.map(function (child) {
                                            return child.label;
                                        }).join(',');
                                        that.form.TypeBrandList.push({ brandid: brandid, brandname: brandname, modellist: modellist });
                                    }
                                    else
                                    {
                                        that.form.TypeBrandList.push({ brandid: brandid, brandname: brandname, modellist:''});
                                    }
                                });
                            }
                        }
                    }
                });
             },
             getBrandModel() {
                   var that = this;
                   ys.ajax({
                    url: '@Url.Content("~/QixingManage/GoodsTypes/GetBrandModel")',
                    type: 'get',
                    success: function (obj) {
                        if (obj.Tag == 1) {
                            that.typebrand = obj.Data;
                            that.typebrand.map(item => {
                                //if (item.children.length == 0) {
                                //    item.children =null;
                                //}
                            })
                        }
                    }
                });
             },
             typeBrandCancel() {
                 this.TypeBrandVisible = false;
             },
             typeBrandSubmit() {
                    var that = this;
                    that.TypeBrandVisible = false;
                    that.form.TypeBrandList = [];
                    console.log(this.selectedNodes);
                    that.selectedNodes.forEach(function(item) {
                        var brandname = item.label;
                        var brandid = item.value;
                        if (item.children !=null) {
                            var modellist = item.children.map(function (child) {
                                return child.label;
                            }).join(',');
                            that.form.TypeBrandList.push({ brandid: brandid, brandname: brandname, modellist: modellist });
                        }
                        else
                        {
                            that.form.TypeBrandList.push({ brandid: brandid, brandname: brandname, modellist:''});
                        }
                    });
             }
         },
         created() {
         },
         mounted() {
             if (id > 0) {
                this.getForm();
             }
             this.getBrandModel();
         },
     });

    function saveForm(index) {
         var postData ={ Id: id };
            postData.type_name = vm.form.type_name;
            postData.IsBrandModel = vm.form.IsBrandModel;
            postData.typeBrands=vm.form.TypeBrandList;
            postData.input_BrandList=JSON.stringify(vm.selectedNodes);
            postData.input_selectedValues=JSON.stringify(vm.selectedValues);
            ys.ajax({
                url: '@Url.Content("~/QixingManage/GoodsTypes/SaveFormJson")',
                type: 'post',
                data: postData,
                success: function (obj) {
                    if (obj.Tag == 1) {
                        ys.msgSuccess(obj.Message);
                        parent.searchGrid();
                        parent.layer.close(index);
                    }
                    else {
                        ys.msgError(obj.Message);
                    }
                }
            });
    }
</script>

